from meiduo_mall.settings import SECRET_KEY

'''
class LoginRequiredMixin(AccessMixin):
    """Verify that the current user is authenticated."""

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            return self.handle_no_permission()
        return super().dispatch(request, *args, **kwargs)

'''
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import JsonResponse


# class LoginRequiredJsonMixin(AccessMixin):
#     """Verify that the current user is authenticated."""
#
#     def dispatch(self, request, *args, **kwargs):
#         if not request.user.is_authenticated:
#             return JsonResponse({'code':400,'errmsg':'请先登录'})
#         return super().dispatch(request, *args, **kwargs)

class LoginRequiredJsonMixin(LoginRequiredMixin):
    def handle_no_permission(self):
        return JsonResponse({'code': 400, 'errmsg': '请先登录'})


from itsdangerous import URLSafeTimedSerializer as Serializer, BadSignature, SignatureExpired


class JWTManager:

    def __init__(self, secret_key=SECRET_KEY):
        self.serializer = Serializer(secret_key)

    def turn_to_token(self, data):
        return self.serializer.dumps(data)

    def turn_back_data(self, token, max_age=3600):

        try:
            return self.serializer.loads(token, max_age=max_age)
        except SignatureExpired:
            # 令牌过期
            return None
        except BadSignature:
            # 令牌无效
            return None
        except Exception as e:
            return None



class OCarts:

    def decode(self,):
        pass

    def encode(self):
        pass
